import { NavController } from 'ionic-angular';
import { InitComponent } from './page/init/init.component';
import { PrintService } from './service/print.service';
import { Message } from './component/primeng/common';
import { OnlineManager } from './common/onlineManager';
import { MdSnackBar } from '@angular/material';
import { OnLineService } from './component/primeng/online/online.module';
import { SystemService } from './service/system.service';
import { GrowlMessageType } from './component/messageBoxService';
import { FNCManager } from './common/fncManager';
import { MessageHandleManager } from './common/messageHandle/msgHandleMg';
import { Component, ChangeDetectorRef, HostListener, ViewChild } from '@angular/core';
import { DataContextManager, SoldOut } from "./model/clerkDataContext";
import { IMessageBoxContainer, MessageBoxService } from "./component/index";
import { NavigateService, ServiceBase } from "./service/index";
import { Router } from '@angular/router';

declare let EventRegistHandle: any;
@Component({
    //moduleId: module.id,
    // selector: 'div[my-app]',
    template: `
        <ion-nav #nav [root]="rootPage"></ion-nav>
        <div load-mask></div>
        <div online class="online-tip"></div>
        <print-container></print-container>
        <router-outlet></router-outlet>`
})
export class AppComponent implements IMessageBoxContainer {
    Title: string;
    Content: string;
    Visible: boolean;
    showOK: boolean = true;
    showCancel: boolean = true;
    showIgnore: boolean = false;
    GrowlMessage: Message[];
    rootPage: any = InitComponent;
    
    @ViewChild("nav") navCtrl: NavController;
    // @HostListener("document:backbutton") backBtn() {
    //     this.navSvr.goBack();
    // }
    // private timer;
    constructor(
        private msgSvr: MessageBoxService,
        private navSvr: NavigateService,
        private router: Router,
        private svr: ServiceBase,
        private ref: ChangeDetectorRef,
        private sysSvr: SystemService,
        public snackBar: MdSnackBar,
        private printSvr: PrintService
    ) {
        DataContextManager.Current.Regist();
        FNCManager.Current.Regsit_AppComponent(this);
        navSvr.registRouter(router);
        navSvr.AuthCheck(window.location.href, true);
        MessageHandleManager.Current.RegistMessageHandle();

        this.OnInit();

    }
    //messageboxService所需要的结果事件
    onResult;
    OnInit() {
        let that = this;
        this.FNCConnect();
        this.checkDevice();
        let ctx = DataContextManager.Current.ClerkCtx;
        EventRegistHandle.RegistHandle("WeakNetwork", () => {
            that.msgSvr.Growl(GrowlMessageType.Error, this.snackBar, "貌似网络不太稳定，可能导致下单失败。");
            that.ref.detectChanges();
        });
        // EventRegistHandle.RegistHandle("CheckEnv", () => {
        //     OnLineService.Current.open();
        // });

        /**
        * 环境检测心跳
        */
        EventRegistHandle.RegistHandle("IsOnlineHeart", () => {
            // that.timer = setInterval(async () => {
            //     let boo = await this.sysSvr.envHeartCheck();
            //     if (!boo) {
            //         EventRegistHandle.Call("CheckEnv");
            //     } else {
            //         OnLineService.Current.reset();
            //     }
            // }, 5000);
            OnlineManager.Current.add(that.checkIsOnline.bind(that), OnLineService.Current.reset.bind(OnLineService.Current), OnLineService.Current.open.bind(OnLineService.Current));
        });

        EventRegistHandle.RegistHandle("FNSConnect", () => {
            that.FNCConnect();
        });
        // this.saveVersion();
    }

    async FNCConnect() {
        if (this.svr.HostIp) {
            //连接FNS 
            await FNCManager.Current.Connect(this.svr.HostIp);
            FNCManager.Current.FNC.RegistMessageHandler("innerMessage", (message) => {
                console.log("收到消息：", message);
                MessageHandleManager.Current.ReceivedMessage(message);
            });
        }
    }

    async checkIsOnline() {
        return this.sysSvr.envHeartCheck();
    }

    /**
     * 检测cordova是否加载完成
     */
    checkDevice() {
        let that = this;
        let timer = setTimeout(() => {
            if ((<any>window).device) {
                that.backBtnEvent();
                that.weakNetEvent();
            } else {
                that.checkDevice();
            }
            clearTimeout(timer);
        }, 500)
    }

    /**
     * 返回按键事件
     */
    backBtnEvent() {
        document.addEventListener("backbutton", () => {
            this.navSvr.goBack();
        }, false);
    }
    /**
     * 弱网检测事件
     */
    weakNetEvent() {
        if ((<any>window).device.wifi) {
            (<any>window).device.wifi.startRssi(rssi => {
                //rssi: 0-25/26-50/51-75/76-100 4个等级， 返回0-100的数字
                if (rssi < 25) {
                    EventRegistHandle.Call("WeakNetwork");
                }
            })
        }
    }

    /**
     * 保存当前版本号
     */
    async saveVersion() {
        let result = this.sysSvr.getVersion();
        if (result) {
            result.then(response => {
                let versionData = response.json();
                localStorage.setItem("version", versionData.version + "");
            })
        }
        // let latestVersion: any = await this.sysSvr.getLatestVersion();
        // if (currentVersion.version != latestVersion.version) {
        //     this.router.navigate(['update'])
        // }
    }
}
